package com.easytouch.core.task;

import com.easytouch.core.Configure;
import com.easytouch.core.utils.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by gulin on 2017/8/18.
 */

public class PickCodeReleaseTask extends Task {
    private Log mLogger = new Log("PickCodeReleaseTask.txt");
    private boolean mIsRelease = true; //是否是撤销

    public PickCodeReleaseTask(final String pCode, final boolean isRelease)
    {
        super(pCode);
        mIsRelease = isRelease;
    }

    @Override
    public void run() {
        String ip = Configure.getConfigData(Configure.CONFIG_PICK_IP);
        if(ip == null || ip.equals(""))
        {
            mLogger.e("提货码服务器IP为空");
            cleanup(-1, "local data error");
            return;
        }
        String portStr = Configure.getConfigData(Configure.CONFIG_PICK_PORT);
        if(portStr == null || portStr.equals(""))
        {
            mLogger.e("提货码服务器端口为空");
            cleanup(-1, "local data error");
            return;
        }
        int port = 0;
        try {
            port = Integer.parseInt(portStr);
        }
        catch (NumberFormatException e)
        {
            mLogger.e("提货码服务器端口转换错误:" + e.getMessage());
            cleanup(-1, "local data error");
            return;
        }

        Socket socket = new Socket();
        InetSocketAddress socAddress = new InetSocketAddress(ip, port);
        InputStream in = null;
        OutputStream out = null;
        try {
            socket.connect(socAddress, 10000);
            in = socket.getInputStream();
            out = socket.getOutputStream();
            //发送数据:11(核销)12(撤销) + 机器号 + 提货码
            String sendStr = (mIsRelease ? "12" : "11") + Configure.getMacNo() + getIdentifier();
            mLogger.i("提货码核销数据发送:" + sendStr);
            out.write(sendStr.getBytes());
            out.flush();
            //读取回应
            String lenStr = read(in, 3); //3位（长度）
            int len = Integer.parseInt(lenStr);
            String receiveMsg = read(in, len);
            mLogger.i("提货码核销数据接收:" + receiveMsg);
            // 2位（提货码长度）+11(核销)12(撤销)+10位提货码+1位状态码(1,表示成功；2，表示失败)
            int codeLen = Integer.parseInt(receiveMsg.substring(0, 2));
            int pos = 2 + 2 + codeLen;
            int resultCode = Integer.parseInt(receiveMsg.substring(pos, pos + 1));
            cleanup(resultCode, "ok");
        }
        catch (UnknownHostException e) {
            mLogger.e("提货码核销发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (SocketTimeoutException e) {// 超时
            mLogger.e("提货码核销发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (IOException e) {
            mLogger.e("提货码核销发生错误:" + e.getMessage());
            cleanup(-2, "net error");
        } catch (NumberFormatException e) {
            mLogger.e("提货码核销发生错误:" + e.getMessage());
            cleanup(-3, "data error");
        } catch (Exception e) {
            mLogger.e("提货码核销发生错误:" + e.getMessage());
            cleanup(-3, "data error");
        } finally {
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
                if (socket != null)
                    socket.close();
            } catch (IOException ex) {
            }
        }
    }

    private void cleanup(final int pResultCode, final String pResultMessage)
    {
        TaskThreadPool.removeIdentifier(getIdentifier());
    }
}
